import 'dart:convert';
import 'dart:io';

import 'package:base_app/utils/file_util.dart';
import 'package:base_app/utils/permission_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import 'base_handler.dart';

class AssetPickerHandler extends BaseHandler {

  @override
  String name = "assetsPicker";

  @override
  void handler(dynamic data, dynamic responseCallback) async {
    bool permission = false;

    String type = 'common';
    if(data != null && data.containsKey('type')) {
      type = data['type'];
    }
    RequestType requestType = RequestType.common;
    if(type == 'image') {
      requestType = RequestType.image;
      permission = await PermissionUtil.getPermissionStatus(Permission.photos);
    }else if(type == 'video') {
      requestType = RequestType.video;
      permission = await PermissionUtil.getPermissionStatus(Permission.videos);
    }else if(type == 'audio') {
      requestType = RequestType.audio;
      permission = await PermissionUtil.getPermissionStatus(Permission.audio);
    }

    if(!permission) {
      return;
    }

    AssetPickerConfig config = AssetPickerConfig(
      maxAssets: 1,
      selectedAssets: [],
      textDelegate: const AssetPickerTextDelegate(),
      requestType: requestType,
      specialItemPosition: SpecialItemPosition.prepend,
      specialItemBuilder: (context, path, length) {
        return Semantics(
          button: true,
          label: "拍照",
          onTapHint: "拍照",
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () async {
              bool hasPermission =
              await PermissionUtil.getPermissionStatus(Permission.camera);
              if (!hasPermission) {
                return;
              }
              if (context.mounted) {
                AssetEntity? entity = await CameraPicker.pickFromCamera(
                    context,
                    pickerConfig:
                    const CameraPickerConfig(enableRecording: false));
                if (entity == null) {
                  return;
                }
                final AssetPicker<AssetEntity, AssetPathEntity> picker =
                context.findAncestorWidgetOfExactType()!;
                final DefaultAssetPickerBuilderDelegate builder =
                picker.builder as DefaultAssetPickerBuilderDelegate;
                final DefaultAssetPickerProvider p = builder.provider;
                await p.switchPath(p.currentPath!);
                p.selectAsset(entity);
              }
            },
            child: const Center(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.camera_alt_outlined,
                      size: 42,
                      color: Color(0xff999999),
                    ),
                    Text(
                      "拍照/录像",
                      style: TextStyle(fontSize: 12, color: Color(0xff999999)),
                    )
                  ],
                )),
          ),
        );
      },
    );
    List<AssetEntity>? assets;
    List<Map<String, String>> list = [];
    assets = await AssetPicker.pickAssets(context, pickerConfig: config);
    if(assets != null && assets.isNotEmpty) {
      for(AssetEntity asset in assets){
        File? file = await asset.file;
        String url = await FileUtil.setFileFromLocalStorage(file!.path);
        list.add({"url": url, "id": asset.id.toString(), "title": asset.title!});
      }
      responseCallback(jsonEncode({"data": list}));
    }else{
      responseCallback(jsonEncode({"data": list}));
    }
  }
}